<template>
  <el-container class="goods-view">
    <el-main>
      <div class="split-title">商品信息</div>
      <div class="sa-m-b-16" v-for="goods in state.goodsList" :key="goods">
        <div class="goods-content sa-flex">
          <sa-image :url="goods.image" size="48"></sa-image>
          <div class="sa-m-l-12">
            <div class="title sa-table-line-1 sa-m-b-8">
              {{ goods.title }}
            </div>
            <div v-if="goods.is_sku" class="sku">
              {{ goods.is_sku ? '多规格' : '' }}
            </div>
          </div>
        </div>
      </div>
      <div class="split-title sa-m-b-16">佣金设置</div>
      <el-form label-width="120px">
        <el-form-item label="是否参与">
          <el-radio-group v-model="state.commission_goods.status">
            <el-radio :label="0">不参与</el-radio>
            <el-radio :label="1">参与</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分销商业绩">
          <el-radio-group v-model="state.commission_goods.commission_order_status">
            <el-radio :label="0">不计入</el-radio>
            <el-radio :label="1">
              <span class="sa-flex">
                计入
                <el-popover
                  placement="top"
                  :width="310"
                  content="关闭则只分佣，不计入分销订单金额和订单数"
                >
                  <template #reference>
                    <el-icon class="warning sa-m-l-8"><Warning /></el-icon>
                  </template>
                </el-popover>
              </span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="佣金规则">
          <el-radio-group v-model="state.commission_goods.self_rules" @change="onChangeSelfRules">
            <el-radio :label="0">默认规则</el-radio>
            <el-radio :label="1" v-if="modal.params.type != 'batch'">独立规则</el-radio>
            <el-radio :label="2">批量规则</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="state.commission_goods.self_rules == 1 || state.commission_goods.self_rules == 2"
          label="分销设置"
        >
          <el-switch
            v-model="state.commission_config_temp.status"
            @change="onChangeCommissionConfigStatus"
            :active-value="1"
            :inactive-value="0"
          />
          <span class="sa-m-l-8">
            {{ state.commission_config_temp.status ? '自定义' : '默认' }}
          </span>
        </el-form-item>
        <el-form-item label="分销层级">
          <el-radio-group
            v-model="state.commission_config_temp.level"
            :disabled="state.commission_config_temp.status == 0"
          >
            <el-radio :label="1">一级</el-radio>
            <el-radio :label="2">二级</el-radio>
            <el-radio :label="3">三级</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分销自购">
          <div>
            <el-radio-group
              v-model="state.commission_config_temp.self_buy"
              :disabled="state.commission_config_temp.status == 0"
            >
              <el-radio :label="0">关闭</el-radio>
              <el-radio :label="1">开启</el-radio>
            </el-radio-group>
            <div class="tip"> 分销自购开启后，分销商自己购买时，下单可以给自己返佣 </div>
          </div>
        </el-form-item>
        <el-form-item label="商品结算方式">
          <div>
            <el-radio-group
              v-model="state.commission_config_temp.reward_type"
              :disabled="state.commission_config_temp.status == 0"
            >
              <el-radio label="goods_price">商品价</el-radio>
              <el-radio label="pay_price">实际支付价</el-radio>
            </el-radio-group>
            <div class="tip">
              商品价: 商品实际售价/规格价，实际支付价:实际支付的费用(不含运费)
            </div>
          </div>
        </el-form-item>
        <el-form-item label="佣金结算方式">
          <el-radio-group
            v-model="state.commission_config_temp.reward_event"
            :disabled="state.commission_config_temp.status == 0"
          >
            <el-radio label="paid">支付后结算</el-radio>
            <el-radio label="confirm">确认收货结算</el-radio>
            <el-radio label="finish">订单完成结算</el-radio>
            <el-radio label="admin">手动打款</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="commission-table">
          <template v-if="state.commission_goods.self_rules == 0">
            <div class="commission-header sa-flex">
              <div class="col-item">分销等级名称</div>
              <template v-for="commission in state.commission_config_temp.level" :key="commission">
                <div v-if="commission == 1" class="col-item commission-item">
                  一级(自购)佣金比例
                </div>
                <div v-if="commission == 2" class="col-item commission-item"> 二级佣金比例 </div>
                <div v-if="commission == 3" class="col-item commission-item"> 三级佣金比例 </div>
              </template>
            </div>
            <div class="commission-content sa-flex" v-for="level in state.levelData" :key="level">
              <div class="col-item">{{ level.name }}</div>
              <template v-for="commission in state.commission_config_temp.level" :key="commission">
                <div class="col-item commission-item">
                  {{ level.commission_rules[`commission_${commission}`] }}%
                </div>
              </template>
            </div>
          </template>
          <template v-if="state.commission_goods.self_rules == 1">
            <div class="commission-header sa-flex">
              <div class="col-item">商品规格</div>
              <div class="col-item">价格</div>
              <div class="col-item">分销等级名称</div>
              <template v-for="commission in state.commission_config_temp.level" :key="commission">
                <div class="col-item commission-item">
                  <template v-if="commission == 1">一级(自购)佣金比例</template>
                  <template v-if="commission == 2">二级佣金比例</template>
                  <template v-if="commission == 3">三级佣金比例</template>
                  <el-popover
                    popper-class="commission-popover"
                    v-model:visible="commissionPopover.flag[commission]"
                    placement="top"
                    :width="220"
                    trigger="click"
                  >
                    <div class="commission-item sa-flex">
                      <el-input
                        v-model="commissionPopover.form.rate"
                        type="number"
                        :disabled="commissionPopover.form.money != ''"
                      >
                        <template #append>%</template>
                      </el-input>
                      <el-input
                        v-model="commissionPopover.form.money"
                        type="number"
                        :disabled="commissionPopover.form.rate != ''"
                      >
                        <template #append>元</template>
                      </el-input>
                    </div>
                    <div class="sa-flex sa-row-right">
                      <el-button
                        class="is-link"
                        type="primary"
                        size="small"
                        @click="onCancelCommissionPopover(commission)"
                        >取消</el-button
                      >
                      <el-button
                        type="primary"
                        size="small"
                        @click="onConfirmCommissionPopover(commission)"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <el-icon class="batch-edit">
                        <Edit />
                      </el-icon>
                    </template>
                  </el-popover>
                </div>
              </template>
            </div>
            <div class="commission-content sa-flex">
              <div class="sa-flex sa-flex-col">
                <div class="sa-flex" v-for="sku in state.detailData.sku_prices" :key="sku">
                  <div class="col-item" :style="{ height: 48 * state.levelData.length + 'px' }">
                    {{ state.detailData?.is_sku ? sku.goods_sku_text.join(',') : '默认规格' }}
                  </div>
                  <div class="col-item" :style="{ height: 48 * state.levelData.length + 'px' }">
                    {{ sku.price }}
                  </div>
                  <div>
                    <div class="col-item" v-for="level in state.levelData" :key="level">
                      {{ level.name }}
                    </div>
                  </div>
                </div>
              </div>
              <div>
                <div v-for="sku in state.commission_goods.commission_rules" :key="sku">
                  <div class="sa-flex" v-for="level in sku" :key="level">
                    <template
                      v-for="commission in state.commission_config_temp.level"
                      :key="commission"
                    >
                      <div v-if="level[commission]" class="col-item commission-item">
                        <el-input
                          v-model="level[commission].rate"
                          type="number"
                          :disabled="level[commission].money != ''"
                        >
                          <template #append>%</template>
                        </el-input>
                        <el-input
                          v-model="level[commission].money"
                          type="number"
                          :disabled="level[commission].rate != ''"
                        >
                          <template #append>元</template>
                        </el-input>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template v-if="state.commission_goods.self_rules == 2">
            <div class="commission-header sa-flex">
              <div class="col-item">商品规格</div>
              <template v-for="commission in state.commission_config_temp.level" :key="commission">
                <div class="col-item commission-item">
                  <template v-if="commission == 1">一级(自购)佣金比例</template>
                  <template v-if="commission == 2">二级佣金比例</template>
                  <template v-if="commission == 3">三级佣金比例</template>
                  <el-popover
                    popper-class="commission-popover"
                    v-model:visible="commissionPopover.flag[commission]"
                    placement="top"
                    :width="220"
                    trigger="click"
                  >
                    <div class="commission-item sa-flex">
                      <el-input
                        v-model="commissionPopover.form.rate"
                        type="number"
                        :disabled="commissionPopover.form.money != ''"
                      >
                        <template #append>%</template>
                      </el-input>
                    </div>
                    <div class="sa-flex sa-row-right">
                      <el-button
                        class="is-link"
                        type="primary"
                        size="small"
                        @click="onCancelCommissionPopover(commission)"
                        >取消</el-button
                      >
                      <el-button
                        size="small"
                        type="primary"
                        @click="onConfirmCommissionPopover(commission)"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <el-icon class="batch-edit">
                        <Edit />
                      </el-icon>
                    </template>
                  </el-popover>
                </div>
              </template>
            </div>
            <div class="commission-content sa-flex">
              <div>
                <div class="col-item" v-for="level in state.levelData" :key="level">
                  {{ level.name }}
                </div>
              </div>
              <div>
                <div
                  class="sa-flex"
                  v-for="level in state.commission_goods.commission_rules"
                  :key="level"
                >
                  <template
                    v-for="commission in state.commission_config_temp.level"
                    :key="commission"
                  >
                    <div v-if="level[commission]" class="col-item commission-item">
                      <el-input
                        v-model="level[commission].rate"
                        type="number"
                        :disabled="level[commission].money != ''"
                      >
                        <template #append>%</template>
                      </el-input>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </template>
        </div>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-auth="'shop.admin.commission.goods.edit'" type="primary" @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive } from 'vue';
  import { api } from '../commission.service';
  import { isEmpty, isObject, cloneDeep } from 'lodash';
  import { ElMessage } from 'element-plus'

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  const state = reactive({
    goodsList: [],
    detailData: {},
    commission_goods: {
      status: 1,
      self_rules: props.modal.params.type != 'batch' ? 0 : 2,
      commission_order_status: 1,
      commission_config: {},
      commission_rules: {},
    },
    defaultCommissionConfig: {
      status: 0,
      level: 2,
      self_buy: 0,
      reward_type: 'goods_price',
      reward_event: 'paid',
    },
    commission_config_temp: {},
    commission_rules: {},
    levelData: [],
  });

  async function getDetail() {
    const { error, data } = await api.goods.detail(props.modal.params.ids);
    if (error === 0) {
      state.goodsList = data.goods;

      if (props.modal.params.type != 'batch') {
        state.detailData = data.goods[0];
      }

      Object.keys(state.defaultCommissionConfig).forEach((key) => {
        if (key != 'status') state.defaultCommissionConfig[key] = data.config[key];
      });

      state.commission_config_temp = cloneDeep(state.defaultCommissionConfig);

      if (isEmpty(state.detailData.commission_goods)) {
        initCommission(state.commission_goods.self_rules);
      } else {
        state.commission_goods = state.detailData.commission_goods;

        if (
          state.detailData.commission_goods.commission_config &&
          state.detailData.commission_goods.commission_config.status
        ) {
          state.commission_config_temp = state.detailData.commission_goods.commission_config;
        }

        initCommission(state.detailData.commission_goods.self_rules);
      }
    }
  }

  function initCommission(type) {
    let rate_money = {
      1: {
        rate: '',
        money: '',
      },
      2: {
        rate: '',
        money: '',
      },
      3: {
        rate: '',
        money: '',
      },
    };
    if (!isObject(state.commission_goods.commission_rules)) {
      state.commission_goods.commission_rules = {};
    }
    if (type == 0) {
      state.commission_goods.commission_rules = null;
    } else if (type == 1) {
      state.detailData.sku_prices.forEach((i) => {
        if (state.commission_goods.commission_rules[i.id]) {
          state.levelData.forEach((j) => {
            if (state.commission_goods.commission_rules[i.id][j.level]) {
              for (let key in state.commission_goods.commission_rules[i.id][j.level]) {
                if (!state.commission_goods.commission_rules[i.id][j.level][key].rate) {
                  state.commission_goods.commission_rules[i.id][j.level][key].rate = '';
                } else if (!state.commission_goods.commission_rules[i.id][j.level][key].money) {
                  state.commission_goods.commission_rules[i.id][j.level][key].money = '';
                }
              }
            } else {
              state.commission_goods.commission_rules[i.id][j.level] = cloneDeep(rate_money);
            }
          });

          for (var level in state.commission_goods.commission_rules[i.id]) {
            let index = state.levelData.findIndex((l) => Number(l.level) == Number(level));
            if (index == -1) {
              delete state.commission_goods.commission_rules[i.id][level];
            }
          }
        } else {
          state.commission_goods.commission_rules[i.id] = {};
          state.levelData.forEach((l) => {
            state.commission_goods.commission_rules[i.id][l.level] = cloneDeep(rate_money);
          });
        }
      });

      for (var sku in state.commission_goods.commission_rules) {
        let index = state.detailData.sku_prices.findIndex((s) => Number(s.id) == Number(sku));
        if (index == -1) {
          delete state.commission_goods.commission_rules[sku];
        }
      }
    } else if (type == 2) {
      state.levelData.forEach((l) => {
        if (state.commission_goods.commission_rules[l.level]) {
        } else {
          state.commission_goods.commission_rules[l.level] = cloneDeep(rate_money);
        }
      });

      for (var level in state.commission_goods.commission_rules) {
        let index = state.levelData.findIndex((l) => Number(l.level) == Number(level));
        if (index == -1) {
          delete state.commission_goods.commission_rules[level];
        }
      }
    }
  }

  async function getLevel() {
    const { data } = await api.level.select({
      sort: 'level',
      order: 'asc',
    });
    state.levelData = data;
  }

  function onChangeSelfRules(self_rules) {
    if (self_rules == 1 || self_rules == 2) {
      state.commission_goods.commission_rules = {};
      if (state.commission_config_temp.status == 0) {
        state.commission_config_temp = cloneDeep(state.defaultCommissionConfig);
      }
    } else if (self_rules == 0) {
      state.commission_goods.commission_rules = null;
      state.commission_config_temp = cloneDeep(state.defaultCommissionConfig);
    }
    initCommission(self_rules);
  }

  function onChangeCommissionConfigStatus(val) {
    if (val == 0) {
      // 默认
      state.commission_config_temp = cloneDeep(state.defaultCommissionConfig);
    } else {
      // 自定义
      if (
        state.detailData.commission_goods &&
        state.detailData.commission_goods.commission_config
      ) {
        state.commission_config_temp = state.detailData.commission_goods.commission_config;
      }

      state.commission_config_temp.status = 1;
    }
  }

  const commissionPopover = reactive({
    flag: {},
    form: {
      money: '',
      rate: '',
    },
  });

  function onConfirmCommissionPopover(cl) {
    if (state.commission_goods.self_rules == 1) {
      for (let sku in state.commission_goods.commission_rules) {
        for (let level in state.commission_goods.commission_rules[sku]) {
          state.commission_goods.commission_rules[sku][level][cl] = cloneDeep(commissionPopover.form);
        }
      }
    } else if (state.commission_goods.self_rules == 2) {
      for (let level in state.commission_goods.commission_rules) {
        state.commission_goods.commission_rules[level][cl] = cloneDeep(commissionPopover.form);
      }
    }
    onCancelCommissionPopover(cl);
  }
  function onCancelCommissionPopover(cl) {
    commissionPopover.flag[cl] = false;
    commissionPopover.form = {
      money: '',
      rate: '',
    };
  }

  async function confirm() {
    const commission_goods = {
      ...state.commission_goods,
    };
    commission_goods.commission_config = JSON.stringify({
      ...state.commission_config_temp,
    });

    let flag = true
    if (commission_goods.self_rules == 1) {
      for (var key1 in commission_goods.commission_rules) {
        for (var key2 in commission_goods.commission_rules[key1]) {
          for (var key3 in commission_goods.commission_rules[key1][key2]) {
            if (key3 <= state.commission_config_temp.level) {
              if ((commission_goods.commission_rules[key1][key2][key3].rate === '' || commission_goods.commission_rules[key1][key2][key3].rate < 0)
                && (commission_goods.commission_rules[key1][key2][key3].money === '' || commission_goods.commission_rules[key1][key2][key3].money < 0)) {
                flag = false
              }
            }
          }
        }
      }
    }
    if (commission_goods.self_rules == 2) {
      for (var key1 in commission_goods.commission_rules) {
        for (var key2 in commission_goods.commission_rules[key1]) {
          if (key2 <= state.commission_config_temp.level) {
            if (commission_goods.commission_rules[key1][key2].rate === '' || commission_goods.commission_rules[key1][key2].rate < 0) {
              flag = false
            }
          }
        }
      }
    }
    if (!flag) {
      ElMessage({
        message: '请将数据填写完整',
        type: 'warning',
      })
      return false
    }

    const { error } = await api.goods.edit(props.modal.params.ids, commission_goods);

    if (error == 0) {
      emit('modalCallBack', { event: 'confirm' });
    }
  }

  onMounted(async () => {
    await getLevel();
    getDetail();
  });
</script>
<style lang="scss" scoped>
  .goods-view {
    .split-title {
      padding: 12px 16px;
      background: var(--sa-table-header-bg);
      border-radius: 4px;
      line-height: 16px;
      font-size: 12px;
      font-weight: 500;
      color: var(--sa-subtitle);
    }
    .goods-content {
      padding: 8px 16px;
      border-bottom: 1px solid var(--sa-border);
      &:last-of-type {
        border-bottom: none;
      }
      .title {
        height: 16px;
        line-height: 16px;
        font-size: 14px;
        font-weight: 500;
        color: var(--sa-font);
      }
      .sku {
        padding: 3px 8px;
        border-radius: 10px;
        background: var(--el-color-primary);
        width: fit-content;
        line-height: 14px;
        font-size: 12px;
        font-weight: 400;
        color: var(--sa-background-assist);
      }
    }
    .commission-table {
      overflow: hidden;
      overflow-x: auto;
    }
    .commission-header {
      border-left: 1px solid var(--sa-border);
      .col-item {
        padding: 0 12px;
        height: 40px;
        line-height: 40px;
        background: var(--sa-table-header-bg);
        border-top: 1px solid var(--sa-border);
      }
    }
    .commission-content {
      border-left: 1px solid var(--sa-border);
    }
    .col-item {
      width: 150px;
      min-width: 150px;
      padding: 0 12px;
      height: 48px;
      line-height: 48px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-right: 1px solid var(--sa-border);
      border-bottom: 1px solid var(--sa-border);
      .el-input {
        margin-right: 12px;
        &:last-of-type {
          margin-right: 0;
        }
      }
      &.commission-item {
        width: 240px;
        min-width: 240px;
      }
    }
    .batch-edit {
      color: var(--el-color-primary);
      margin-left: 8px;
    }
  }
  .commission-popover {
    .commission-item {
      margin-bottom: 12px;
      .el-input {
        margin-right: 12px;
        &:last-of-type {
          margin-right: 0;
        }
      }
    }
  }
</style>
